//
//  UIColor+Initialize.swift
//  LGMusic
//
//  Created by 梁尚嘉 on 2017/3/27.
//  Copyright © 2017年 LimeGah. All rights reserved.
//

import UIKit

extension UIColor {



    /// 用16进制字符串生成对应的颜色对象UIColor
    ///
    /// - Parameter hexString: 16进制颜色字符串
    /// - Returns: UIColor
    class func color(with hexString:String) -> UIColor {
        return self.color(hexString:hexString, alpha: 1.0)
    }


    //Dependence
    class func color(hexString:String, alpha:CGFloat) -> UIColor {

        //删除字符串中的空格
        var cString = hexString.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()

        //String should be 6 or 8 characters
        if cString.characters.count < 6 {
            return UIColor.clear
        }

        // strip 0X if it appears
        //如果是0x开头，那么截取字符串，字符串从索引为2的位置开始，一直到末尾
        if cString.hasPrefix("0X") {
            cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 2))
        }

        //如果是#开头的，那么截取字符哇咔咔字符串从索引为1的位置开始，一直到末尾
        if cString.hasPrefix("#") {
            cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 1))
        }

        if cString.characters.count != 6 {
            return UIColor.clear
        }


        //red
        var fromIndex = cString.index(cString.startIndex, offsetBy: 0)
        var toIndex = cString.index(cString.startIndex, offsetBy: 2)
        let rString = cString.substring(with: fromIndex..<toIndex)
        //green
        fromIndex = cString.index(cString.startIndex, offsetBy: 2)
        toIndex = cString.index(cString.startIndex, offsetBy: 4)
        let gString = cString.substring(with: fromIndex..<toIndex)
        //blue
        fromIndex = cString.index(cString.startIndex, offsetBy: 4)
        toIndex = cString.index(cString.startIndex, offsetBy: 6)
        let bString = cString.substring(with: fromIndex..<toIndex)


        return UIColor.init(red: CGFloat(self.changeToInt(numStr: rString))/255.0, green: CGFloat(self.changeToInt(numStr: gString))/255.0, blue: CGFloat(self.changeToInt(numStr: bString))/255.0, alpha: alpha)
    }

    class func changeToInt(numStr:String) -> Int {

        let str = numStr.uppercased()
        var sum = 0
        for i in str.utf8 {
            //0-9 从48开始
            sum = sum * 16 + Int(i) - 48
            if i >= 65 {
                //A~Z 从65开始，但初始值为10
                sum -= 7
            }
        }
        return sum
    }
}


